import json

from django import forms
from django.http import JsonResponse

from hot import models


# Create your views here.

# 获取数据

def get_data(request, name, priority):
    data = models.ContentManage.objects.filter(content_category__category_name=name, active=1,
                                               content_priority=priority).all()
    lst = []
    for i in data:
        content = {
            'title': i.content_title,
            'detail': i.content_detail,
            'priority': i.content_priority,
            'imgs': [],
        }
        for j in i.content_imgs.all():
            print(j.content_img.name)
            content['imgs'].append(j.content_img.name.replace('unload/' , ''))
        lst.append(content)
    # 返回JSON响应
    return JsonResponse({'data': lst}, safe=False)


from django.core.validators import RegexValidator


class LiuYanForm(forms.Form):
    msg_name = forms.CharField(max_length=32, error_messages={'required': '姓名不能为空'})
    msg_phone = forms.CharField(validators=[RegexValidator(regex=r'^1[3-9]\d{9}$', message='请输入有效的手机号码')])
    msg_text = forms.CharField()


def post_liuyan(request):
    """留言内容"""
    if request.method == 'POST':
        print(request.body)
        form = LiuYanForm(json.loads(request.body))
        if not form.is_valid():
            return JsonResponse({'code': '-1', 'data': form.errors})
        models.Message.objects.create(**form.cleaned_data)
        return JsonResponse({'code': '200', 'data': '发送成功!'})


def judge_phone(request):
    user_agent = request.META.get('HTTP_USER_AGENT')

    if 'Android' in user_agent:
        return JsonResponse({'status': 200, 'data': 'Android'})
    elif 'iPhone' in user_agent:
        return JsonResponse({'status': 200, 'data': 'iPhone'})
    else:
        return JsonResponse({'status': 200, 'data': 'Pc'})
